<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Libraries\ValidateCode;
use Hash;
use DB;
use Intervention\Image\ImageManagerStatic as Image;//缩放
//会员模块
class MemberController extends Controller
{
    /**
     * 会员列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // return 444;
        $data = DB::table('member') 
            -> where(function($query) use ($request){
                $query -> where('permission',1) 
                ->where('name','like','%'.$request 
                -> input('keywords').'%');
           })-> paginate($request -> input('num',10));
        return view('admin/member/member/index',['data' => $data,'request' => $request  -> all()]);
    }

    /**
     * 添加会员
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin/member/member/create');
    }

    /**
     * 处理添加会员
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request -> except('_token','code');
        // dd($data); 
       
        $this->validate($request, [
            //验证规则，required(不为空)
             'name' => 'required|min:2|max:10',
            'password' => 'required|min:4|max:8',
            'repassword' => 'required|same:password',
            'email' => 'required|email',
            'phone' => 'required|numeric',
            'code' => 'required',
        ],[
             // //错误提醒
             'name.required' => '会员名称不能为空',
             'name.min' => '会员名称在0-10位',
             'name.max' => '会员名称在0-10位',
             'password.required' => '密码不能为空',
             'password.min' => '密码4~8位',
             'password.max' => '密码4~8位',
             'repassword.required' => '确认密码不能为空',
             'repassword.same' => '确认密码与密码不一致',
             'email.required' => '邮箱不能为空',
             'email.email' => '邮箱格式不正确',
             'phone.required' => '手机号码不能为空', 
             'phone.numeric' => '手机号码格式不正确或不少于11位',
             'code.required' => '验证码不能为空',             
        ]);       
        $name = DB::table('member') -> lists('name');
         $request -> flash(); 
        if(in_array($data['name'],$name))
        {
            return back() -> with(['error' => '该账号已存在，请重新输入']);
        }

        $phone = DB::table('member') -> lists('phone');
        $request -> flash();
        if(in_array($data['phone'],$phone))
        {
            return back() -> with(['error' => '该手机号已注册，请重新输入']);
        }

        $email = DB::table('member') -> lists('email');
        $request -> flash();
        if(in_array($data['email'],$email))
        {
            return back() -> with(['error' => '该邮箱已注册，请重新输入']);
        }

         // 检测验证码
        $code = $request -> input('code');
        // dd(session('code'));
        $request -> flash();      
        if($code != session('code'))
        {
            return back() -> with(['error' => '验证码错误']);
        }

        // 删除repassword
        unset($data['repassword']);
        //密码加密;
        $data['password'] = Hash::make($data['password']);
        //处理pic字段
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                //获取后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                // echo $suffix;

                //随机文件名称
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                
                $data['pic'] = '/uploads/member/'.$fileName;
                // dd($data);
                //将文件移入指定文件夹中
                $request -> file('pic') -> move('./uploads/member/',$fileName); 
                
                // 等比缩放start
                $fname = './uploads/member/' . '/' . $fileName;//缩放
                $srcarr = getimagesize($fname);
                $w=200;
                $h=200;
                if($w/$srcarr[0] > $h/$srcarr[1]){
                    $bili = $h/$srcarr[1];
                }else{
                    $bili = $w/$srcarr[0];
                }
                $nw = floor($srcarr[0]*$bili);
                $nh = floor($srcarr[1]*$bili);
                $img = Image::make($fname)->resize($nw,$nh)->save($fname);//缩放
                //等比缩放end
                
            }     
        }
           //处理登录状态,1离线2在线
           //$data['logged'] = 2;

           //处理禁用状态,1可用2禁用
           //$data['disabled'] = 1;

            //处理会员昵称
            $data['nickname'] = $data['name'];

            //处理会员注册时间
            $data['rtime'] = time();

            // 执行添加
            $res = DB::table('member') -> insert($data);
            // dd($res);
            //判断;       
            if($res)
            {
                return redirect('admin/member') -> with(['success' => '添加成功']);
            }else
            {
                return back() -> with(['error' => '添加失败']);
            }

    }

    /**
     * 会员详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = DB::table('member') -> where('member_id',$id) -> first();
        return view('admin/member/member/show',['data' => $data]); 
    }

    /**
     * 更改会员
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // return $id;
        $data = DB::table('member') -> where('member_id','=',$id) -> first();
        // dd($data);
        return view('admin/member/member/edit',['data' => $data]);

    }

    /**
     * 处理更改会员
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request -> except('_token','_method','oldPic');
        // dd($data);
        $this->validate($request, [
            //验证规则，required(不为空)
            'nickname' => 'max:8',
            'email' => 'email',
            'phone' => 'required|numeric',
            // 'code' => 'required',
        ],[
             //错误提醒
             'nickname.max' => '昵称不能超过8位',
             'email.email' => '邮箱格式不正确',
             'phone.required' => '手机号码不能为空', 
             'phone.numeric' => '手机号码格式不正确或不少于11位',
             // 'code.required' => '验证码不能为空',             
        ]);
        $oldPic = '.'.$request -> input('oldPic');
        // return $oldPic;
        //处理图片
        if($request ->hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                //获取后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                // echo $suffix;

                //随机文件名称
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                
                $data['pic'] = '/uploads/member/'.$fileName;
                // dd($data);
                //将文件移入指定文件夹中
                $request -> file('pic') -> move('./uploads/member/',$fileName); 


                //等比缩放start
                $fname = './uploads/member/' . '/' . $fileName;//缩放
                $srcarr = getimagesize($fname);
                $w=200;
                $h=200;
                if($w/$srcarr[0] > $h/$srcarr[1]){
                    $bili = $h/$srcarr[1];
                }else{
                    $bili = $w/$srcarr[0];
                }
                $nw = floor($srcarr[0]*$bili);
                $nh = floor($srcarr[1]*$bili);
                $img = Image::make($fname)->resize($nw,$nh)->save($fname);//缩放
                //等比缩放end

                //更新的同时删除旧图片
                if($oldPic != '.')
                {
                    if(file_exists($oldPic))
                    {
                        unlink($oldPic);//删除旧图片
                    }
                }
               
            }

        }

        //更新数据
        $res = DB::table('member') -> where('member_id',$id) -> update($data);    
        // dd($res);
        if($res)
        {
            return redirect('/admin/member') -> with(['success' => '更新成功']);
        }else
        {
            return back() -> with(['error' => '更新失败']);
        }

    }

    /**
     * 添加会员验证码
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function v_code($id)
    {   
        $vc=new ValidateCode();
        $vc->doimg();
        session(['code' => $vc->getCode()]);
        
    }
}
